package cn.xawl.gulimall.product.exception;

import cn.xawl.common.exception.BizCodeEnum;
import cn.xawl.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author lh
 * @date 2020/06/22 13:31:35
 **/
@Slf4j
@RestControllerAdvice
public class ProductExceptionHandler {
    /**
     * 处理提交数据不合法异常
     * @param e 异常信息
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R validException(MethodArgumentNotValidException e) {
        log.error("数据不合法{}", e.getMessage());
        BindingResult result = e.getBindingResult();
        Map<String, String> errorMap = new HashMap<>();
        result.getFieldErrors().forEach((error) -> {
            String errorMessage = error.getDefaultMessage();
            String errorField = error.getField(); //不合法字段
            errorMap.put(errorField, errorMessage); //不合法信息
        });
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(), BizCodeEnum.VALID_EXCEPTION.getMsg()).put("data", errorMap);
    }

    /**
     * 处理其他异常
     * @param throwable 抛出的异常
     */
    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable) {
        log.error(throwable.getMessage());
        System.out.println(throwable.getMessage());
        Map<String, String> errMap = new HashMap<>();
        errMap.put("msg", throwable.getMessage());
        return R.error(BizCodeEnum.UNKNOWN_EXCEPTION.getCode(), BizCodeEnum.UNKNOWN_EXCEPTION.getMsg())
                .put("data", errMap);
    }

}
